package org.web.datajpa.aop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.web.datajpa.constant.ResultEnum;
import org.web.datajpa.exception.ResultException;
import org.web.datajpa.util.ResultUtil;
import org.web.datajpa.vo.Result;

/**
 * 统一异常处理，使用增强控制器-@RestControllerAdvice
 *
 * @author xiaopeng
 * @version 1.0
 */
@RestControllerAdvice
@Slf4j
public class ExceptionHandle {
    //定义异常处理方法
    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        if (e instanceof ResultException) {
            ResultException re = (ResultException) e;
            //抛出自定义异常错误
            log.info("自定义异常错误:" + re.getMessage());
            return ResultUtil.error(re.getCode(), re.getMessage());
        }
        //未知错误
        log.info("未知错误:" + e.getMessage());
        return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
    }
}
